#include "SplineFourier.h"
#include "math.h"


//-------------------------------------

SplineFourier::SplineFourier() :
    SplineBase(),
    b( 0 )
{
    SetInterpolationDotCnt();
    SetPower();
}

//-------------------------------------

void SplineFourier::allocFactors()
{
    if( N )
    {
        a = new double [ N ];
        b = new double [ N ];

        if( a && b )
        {
            for( int i=0; i<N; i++ )
            {
                a[ i ] = 0;
                b[ i ] = 0;
            }
        }
    }
}

//-------------------------------------

void SplineFourier::calcFactors()
{
    if( N )
    {
        for( int i=0; i < N; i++ )
        {
            for( int n=0; n < yVec->count(); n++ )
            {
                a[ i ] += yVec->at( n ) * cos( M_PI/180 * n*xVec->at( n ) );
                b[ i ] += yVec->at( n ) * sin( M_PI/180 * n*xVec->at( n ) );
            }
            a[ i ] *= 2.0/double(N);
            b[ i ] *= 2.0/double(N);
        }
    }
}

//-------------------------------------

void SplineFourier::freeFactors()
{
    if( a && b )
    {
        delete [] a;
        delete [] b;
        a = 0;
        b = 0;
    }
}

//-------------------------------------

void SplineFourier::Recalculate()
{
    if( N == 0 )
        return;

    if( xVec == NULL && yVec == NULL )
        return;

    double step;
    double currX;
    double nextX;

    allocFactors();
    calcFactors();

    int j = 0;

    for( int i=0; i < 1/*xVec->count()-1*/; i++ )
    {
        currX = xVec->at( i );

        new_xVec.append( currX );
        new_yVec.append( yVec->at( i ) );

        /*if( xVec->count() > 2 )
            nextX = xVec->at( i+1 );
        else*/
            nextX = xVec->at( i );

        step = ( nextX - currX ) / division;
        if( step )
        {
            currX += step;
            for( j=1; j < division; j++ )
            {
                interpolateData( currX );
                currX += step;
            }
        }
    }
    //new_xVec.append( xVec[ xVec->count()-1 ] );
    //new_yVec.append( yVec[ yVec->count()-1 ] );

    freeFactors();
}

//-------------------------------------

void SplineFourier::interpolateData( double & X )
{
    new_xVec.append( X );

    double Y = 0;
    for( int i=0; i < N; i++ )
        Y += a[ i ] * cos( M_PI/180 * i * X ) + b[ i ] * sin( M_PI/180 * i * X );

    new_yVec.append( Y );
}

//-------------------------------------








